<template>
  <div>
    <SearchForm @search="getTableData" @reset="resetSearch">
      <el-col :span="8" :xs="24" v-show="$permiss[1618]">
        <el-form-item :label="$t('所属租户')">
          <el-select v-model="page.tenantId" @change="tenantChange" style="width: 100%">
            <el-option v-for="item in tenantList" :key="item.adminUserId" :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[1620]">
        <el-form-item :label="$t('APP名称')">
          <el-select style="width: 100%" v-model="page.productName" clearable>
            <el-option v-for="item in productList" :key="item.productId" :label="item.appName"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('日期')">
          <el-date-picker
              v-model="page.timeValue"
              style="width: 100%"
              type="daterange"
              range-separator="~"
              unlink-panels
              :clearable="false"
              value-format="yyyy-MM-dd"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>

    </SearchForm>
    <el-card shadow="never" style="margin-top: 10px">
      <Table :tableData="tableData" border :table-column="tableColumn" :page="page" @handleSizeChange="handleSizeChange"
             @handleCurrentChange="handleCurrentChange" :loading="loading">
        <template slot="six" slot-scope="{row}">
          <span style="font-size:14px;text-align: center">{{ row.six }}</span>
        </template>
        <template slot="seven" slot-scope="{row}">
          <span v-html="reduceRate(row.seven,row.six,row)"></span>
        </template>
        <template slot="eight" slot-scope="{row}">
          <span v-html="reduceRate(row.eight,row.seven,row)"></span>
        </template>
        <template slot="nine" slot-scope="{row}">
          <span v-html="reduceRate(row.nine,row.eight,row)"></span>
        </template>
        <template slot="ten" slot-scope="{row}">
          <span v-html="reduceRate(row.ten,row.nine,row)"></span>
        </template>
        <template slot="eleven" slot-scope="{row}">
          <span v-html="reduceRate(row.eleven,row.ten,row)"></span>
        </template>
        <template slot="twelve" slot-scope="{row}">
          <span v-html="reduceRate(row.twelve,row.eleven,row)"></span>
        </template>
        <template slot="thirteen" slot-scope="{row}">
          <span v-html="reduceRate(row.thirteen,row.twelve,row)"></span>
        </template>
        <template slot="fourteen" slot-scope="{row}">
          <span v-html="reduceRate(row.fourteen,row.thirteen,row)"></span>
        </template>
        <template slot="fifteen" slot-scope="{row}">
          <span v-html="reduceRate(row.fifteen,row.fourteen,row)"></span>
        </template>
        <template slot="sixteen" slot-scope="{row}">
          <span v-html="reduceRate(row.sixteen,row.fifteen,row)"></span>
        </template>
        <template slot="seventeen" slot-scope="{row}">
          <span v-html="reduceRate(row.seventeen,row.sixteen,row)"></span>
        </template>
        <template slot="eighteen" slot-scope="{row}">
          <span v-html="reduceRate(row.eighteen,row.seventeen,row)"></span>
        </template>
        <template slot="nineteen" slot-scope="{row}">
          <span v-html="reduceRate(row.nineteen,row.eighteen,row)"></span>
        </template>
        <template slot="twenty" slot-scope="{row}">
          <span v-html="reduceRate(row.twenty,row.nineteen,row)"></span>
        </template>
      </Table>
    </el-card>
  </div>
</template>

<script>
import {selectTenant, selectProduct,} from "@/api/system";
import {
  fetchTimeShareRegisterReport,
  fetchTimeShareRegisterTotal
} from '@/api/user'
import {dateFormatSection, defaultTimeDate} from "@/utils/tools";

export default {
  name: "marketingReportTimeShare",
  data() {
    return {
      page: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
        timeValue: defaultTimeDate(7)
      },
      tableColumn: [
        {label: this.$t('时间'), prop: 'time', minWidth: 100, fixed: 'left'},
        {label: '0-6', prop: 'six', align: 'center', minWidth: 100, slot: 'six'},
        {label: '7', prop: 'seven', align: 'left', minWidth: 100, slot: 'seven'},
        {label: '8', prop: 'eight', align: 'left', minWidth: 100, slot: 'eight'},
        {label: '9', prop: 'nine', align: 'left', minWidth: 100, slot: 'nine'},
        {label: '10', prop: 'ten', align: 'left', minWidth: 100, slot: 'ten'},
        {label: '11', prop: 'eleven', align: 'left', minWidth: 100, slot: 'eleven'},
        {label: '12', prop: 'twelve', align: 'left', minWidth: 100, slot: 'twelve'},
        {label: '13', prop: 'thirteen', align: 'left', minWidth: 100, slot: 'thirteen'},
        {label: '14', prop: 'fourteen', align: 'left', minWidth: 100, slot: 'fourteen'},
        {label: '15', prop: 'fifteen', align: 'left', minWidth: 100, slot: 'fifteen'},
        {label: '16', prop: 'sixteen', align: 'left', minWidth: 100, slot: 'sixteen'},
        {label: '17', prop: 'seventeen', align: 'left', minWidth: 100, slot: 'seventeen'},
        {label: '18', prop: 'eighteen', align: 'left', minWidth: 100, slot: 'eighteen'},
        {label: '19', prop: 'nineteen', align: 'left', minWidth: 100, slot: 'nineteen'},
        {label: '20-23', prop: 'twenty', align: 'left', minWidth: 100, slot: 'twenty'},
      ],
      tableData: [],
      productList: [],
      tenantList: [],
      loading: false
    }
  },
  async mounted() {
    await selectTenant().then(res => {
      this.tenantList = res.data
      if (this.tenantList.length) {
        this.$set(this.page, 'tenantId', this.tenantList[0].adminUserId)
      }
    })
    selectProduct().then(res => {
      this.productList = res.data
    })
    this.getTableData()
  },
  methods: {
    async getTableData() {
      const [datetimeStart, datetimeEnd] = dateFormatSection(this.page.timeValue)
      const params = {
        ...this.page,
        datetimeStart, datetimeEnd
      }
      delete params.timeValue
      this.loading = true
      const res = await fetchTimeShareRegisterReport(params)
      if (res.code === 1) {
        const {total, list} = res.data
        this.tableData = list
        this.page.total = total
        await this.getTotal(params)
        this.loading = false
      } else {
        this.loading = false
      }
    },
    async getTotal(params) {
      const res = await fetchTimeShareRegisterTotal(params)
      if (res.code === 1) {
        if (this.tableData.length > 0) {
          const average = res.data.find(item => item.type === 2)
          const total = res.data.find(item => item.type === 1)
          this.countAverageNum(average)
          this.tableData.unshift({...total, time: this.$t('合计')})
        } else {
          this.tableData = []
        }
      }
    },
    // 计算平均数
    countAverageNum(data) {
      const averageObj = {}
      for (const key in data) {
        if (data[key]) {
          averageObj[key] = (data[key] / data['num']).toFixed(2)
        } else {
          averageObj[key] = 0
        }
      }
      this.tableData.unshift({...averageObj, time: this.$t('平均数')})
    },
    // 计算增长率
    reduceRate(currentValue, previousValue, rows) {
      if (rows.time === this.$t('合计') || rows.time === this.$t('平均数')) {
        return `
        <div style="font-size: 16px;text-align: center;">${currentValue}</div>
        `
      }
      // 当前值
      const cur = currentValue || 0
      // 前一个值
      const pre = previousValue || 0
      const upValue = (cur - pre).toFixed(0)
      /**
       * @param curValue 当前值
       * @param upValue 增长值
       * @param trend up: 涨   flat:平
       * @return {string}
       */
      const formatText = (curValue, upValue, trend) => {
        const up = trend === 'up'
        return `
        <div style="font-size:16px;position:relative;">${curValue}
               <div style="color:${up ? 'red' : 'gray'};font-size:8px;position:absolute;top: -6px;right: 0px" >+${upValue <= 0 ? '0' : upValue}</div>
        </div>
        </div>
      `
      }
      if (upValue > 0) {
        return formatText(cur, upValue, 'up')
      } else {
        return formatText(cur, upValue, 'flat')
      }
    },
    resetSearch() {
      this.page = {
        pageSize: 10,
        pageNum: 1,
        total: 0
      }
      this.getTableData()
    },
    tenantChange(value) {
      selectProduct({adminUserId: value}).then(res => {
        this.productList = res.data
        this.$set(this.page, 'productName', null)
      })
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
  }
}
</script>

<style scoped>

</style>
